<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\PetProduct;
use App\Models\PetProductCate;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Storage;

class PetProductController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new PetProduct(), function (Grid $grid) {
            // 开启字段选择器功能
            $grid->showColumnSelector();

            $grid->column('id')->sortable();
            $grid->column('cate_id')->display(function ($cate_id) {
                if ($cate_id) {
                    $data = \App\Models\PetProductCate::find($cate_id);
                    return $data->title;
                } else {
                    return '暂无分类';
                }

            });
            $grid->column('name')->editable();
            $grid->column('image')->image();
//            $grid->column('slider_image');
            $grid->column('order')->sortable()->editable();
            $grid->column('price');
            $grid->column('is_show')->switch();
//            $grid->column('spec_type');
//            $grid->column('deduct_stock_type');
//            $grid->column('store_info');
            $grid->column('stock');
            $grid->column('is_postage')->switch();
            $grid->column('browse');
            $grid->column('created_at');
            $grid->column('updated_at')->sortable();

//数据导出
            $grid->export()->rows(function (array $rows) {
                foreach ($rows as $index => &$row) {
                    $data = PetProductCate::find($row['cate_id']);
                    $row['cate_id'] = $data->title;
                    if ($row['is_show']) {
                        $row['is_show'] = '是';
                    } else {
                        $row['is_show'] = '否';
                    }
                    if ($row['is_postage']) {
                        $row['is_postage'] = '是';
                    } else {
                        $row['is_postage'] = '否';
                    }
                }

                return $rows;
            });

            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');

            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new PetProduct(), function (Show $show) {
            $show->field('id');
            $show->cate_id()->as(function ($cate_id) {
                $data = PetProductCate::find($cate_id);
                if ($data) {
                    return $data->title;
                } else {
                    return '未分类';
                }
            });
            $show->image()->image();
            $show->slider_image()->image();
            $show->field('name');
            $show->field('order');
            $show->field('price');
            $show->field('cost');
            $show->is_show()->using(['0' => '隐藏', '1' => '显示']);
            $show->field('spec_type');
            $show->field('deduct_stock_type');
            $show->field('store_info');
            $show->field('stock');
            $show->is_postage()->using(['0' => '不包邮', '1' => '包邮']);
            $show->field('browse');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new PetProduct(), function (Form $form) {
            $form->display('id');
            $form->text('name')->required();
            $form->select('cate_id','产品分类')->options('productCategory')->required();
            $form->image('image')->required();
            $form->image('slider_image');
            $form->number('order');
            $form->number('price')->required();
            $form->number('cost')->required();
            $form->number('spec_type');
            $form->number('deduct_stock_type', '库存减少方式（0：下单即减少，1：付款即减少）');
            $form->editor('store_info');
            $form->number('stock');
            $form->number('browse');
            $form->switch('is_postage');
            $form->switch('is_show');
            $form->display('created_at');
            $form->display('updated_at');
            $sku_params = [
//                [
//                    'name' => '拓展列第一列', // table 第一行 title
//                    'field' => 'column1', // input 的 field_name 名称
//                    'default' => '5', // 默认值
//                ],
//                [
//                    'name' => '拓展列第二列',
//                    'field' => 'column2',
//                    'default' => '',
//                ],
            ];
            $form->sku('sku', json_encode($sku_params))->display(true)->customFormat(function ($value) use ($form) {
                if ($value === null) {
                    // 这里是给sku喂数据， 数据格式为
                    $data = new \stdClass();

                    $data->attrs = [
                        '颜色' => [
                            '红色',
                            '蓝色',
                        ],
                        '大小' => [
                            '20',
                            '40'
                        ],

                    ];
                    $sku =  DB::table('pet_store_product_attr_result')->where('product_id',52)->first();
                    $sku1 = json_decode($sku->result,true);
                    $data->sku = $sku1;
                    return json_encode($data);
                }
                return null;
            });

            // 可以用saved回调，等该模型保存完后，再进行处理
            $form->saved(function (Form $form, int $result) {
                if ($result) {
                    $sku = json_decode($form->input('sku'));
                    $attrs = $sku->sku;
                    $res = json_encode($attrs);
                    // 这边拿到sku的数据就自己处理吧
                    dump($res);
                    DB::table('pet_store_product_attr_result')->insert([
                        'product_id'=>$result,
                        'result'=>$res,
                        'change_time'=>date("Y-m-d H:i:s"),
                        'type'=>0
                    ]);
                }
            });

            $form->footer(function ($footer) {

                // 去掉`查看`checkbox
                $footer->disableViewCheck();

                // 去掉`继续编辑`checkbox
                $footer->disableEditingCheck();

                // 去掉`继续创建`checkbox
                $footer->disableCreatingCheck();
            });
        });
    }

        /**
         * 上传商品规格图片
         *
         * @param Request $request
         *
         * @return string[]
         */
        public function skuImage(\Illuminate\Http\Request $request)
    {
        if ($request->has('file')) {
            $file = $request->file('file');
            $disk = Storage::disk('cosv5');
            $url = 'sku';
            $res = $disk->put($url, $file);
            // 返回格式
            return ['url' => 'http://petpark.jy:8033/uploads/sku/' . $res];
        }
        return [];
    }



}
